package com.twohand.admin.Config;

import com.github.binarywang.wxpay.exception.WxPayException;
import com.twohand.utils.Response.BaseException;
import com.twohand.utils.Response.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

@RestControllerAdvice
public class GlobalException {
    /**
     * 空指针异常
     */
    Logger log = LoggerFactory.getLogger(GlobalException.class);
    @ExceptionHandler(NullPointerException.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public Response handleTypeMismatchException(NullPointerException ex) {
        ex.printStackTrace();
        return Response.fail("暂无数据:"+ex.getMessage());
    }
    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseBody
    public Response handleNoFoundException(NoHandlerFoundException e){
        e.printStackTrace();
        return Response.noFound();
    }
    //    自定义异常
    @ExceptionHandler(BaseException.class)
    @ResponseBody
    public Object baseException(BaseException e){
        e.printStackTrace();
        return Response.customException(e);
    }
    @ExceptionHandler(DataIntegrityViolationException.class)
    @ResponseBody
    public Object sqlException(DataIntegrityViolationException e){
        e.printStackTrace();
        log.error(e.getMessage());
        return Response.fail(e.getMessage());
    }
    @ExceptionHandler(WxPayException.class)
    @ResponseBody
    public Object wxException(WxPayException e){
        e.printStackTrace();
        log.error(e.getCustomErrorMsg());
        return Response.fail(e.getCustomErrorMsg());
    }
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Object handler(Exception e){
        e.printStackTrace();
        log.error(e.getMessage());
        return Response.fail(e.getMessage());
    }
}